/*
 * Copyright 2013 Pavel Stastny <pavel.stastny at gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aplikator.server.processes.impl.processes.ipc.sharedfolder;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Pavel Stastny <pavel.stastny at gmail.com>
 */
public class SharedFolderSingleton {
    
    
    private static Map<String, SharedFolderSingleton> INSTANCES = new HashMap<String, SharedFolderSingleton>();

    protected int counter = 0;
    private File busFolder;
    private String appname;
    
    private SharedFolderSingleton(String appname) {
        this.appname = appname;
        String userHome = System.getProperty("user.home");
        this.busFolder = new File(new File(userHome), ".aplikator"+File.separator+"processbus"+File.separator+this.appname);
        if (!this.busFolder.exists()) {
            this.busFolder.mkdirs();
        }
    }

    public synchronized static SharedFolderSingleton getSharedFolder(String appname) {
        if (!INSTANCES.containsKey(appname)) {
            INSTANCES.put(appname, new SharedFolderSingleton(appname));
        }
        return INSTANCES.get(appname);
    }
    
    public File getFolder() {
        return this.busFolder;
    }
    
    private int allocCounter() {
        counter ++;
        return counter;
    }
    
    public synchronized File allocFileName(String fname) throws IOException {
        // big counter
        int c = allocCounter();
        // fname counter
        int mcounter = 0;
        File folder = getFolder();
        File f = new File(folder,c+"_"+fname+"."+mcounter);
        while(f.exists()) { 
            mcounter++; 
            f = new File(folder,c+"_"+fname+"."+mcounter);
        }
        f.createNewFile();
        return f;
    }
}
